import { useUserStore } from '@/stores/user';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import router from '@/routers/router';

// axios基础配置项
const httpInstance = axios.create({
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
    timeout: 5000
});

// 请求拦截器
httpInstance.interceptors.request.use(config => {
    // 从Pinia中获取toke，并在请求中携带
    const userStore = useUserStore();
    const token = userStore.userData?.token;
    if (token) config.headers.Authorization = `Bearer ${token}`;
    return config;
}, e => Promise.reject(e));

// 响应拦截器
httpInstance.interceptors.response.use(response => response, e => {
        ElMessage({ type: 'warning', message: e.response.data.msg });
        // 拦截401Token失效响应
        if (e.response.status === 401) {
            const userStore = useUserStore();
            userStore.clearUserData();
            router.push('/login');
        }
    return Promise.reject(e);
});

export default httpInstance;